package epam.bookShelf.actions;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import epam.bookShelf.actors.Reader;
import epam.bookShelf.database.ReaderDAO;
import epam.bookShelf.web.ServletListener;

/**
 * Login action (add AUTH field to user session)
 * @author Pustovit Michael, pustovitm@gmail.com
 */
public class LoginAction extends Action {

	@Override
	public void run(HttpServletRequest request, HttpServletResponse response,
			ServletContext context) throws ServletException, IOException 
	{
		String login = request.getParameterValues("login")	[0];
		String pass  = request.getParameterValues("pass")	[0];

		if (login != null && login.length() > 0) 
		{
			ReaderDAO readDao = new ReaderDAO(ServletListener.getDAO());
			
			Reader reader = readDao.readReader(login);
			
			if (reader != null) {
				if (reader.getPass().equalsIgnoreCase(pass))
				{
					request.getSession(true).setAttribute("auth", Boolean.TRUE);
		
					context.getRequestDispatcher("/index.html").forward(request,
							response);
				}
				
				return;
			}			
		} 
			
		final PrintWriter w = response.getWriter();

		w.write("<html><head>");
		w.write("<meta http-equiv=Refresh content=\"5; url="
				+ request.getContextPath() + "login.html\">");
		w.write("</head>");
		w.write("<body>");
		w.write("Wrong login or password. ");
		w.println("<a href=\"" + request.getContextPath()
				+ "/index.html\">Try again</a>");
		w.write("</body></html>");
	}

}
